#include "../unp.h"

/**
 * gcc -g -o tcpserv01 tcpserv01.c ../lib/error.o ../lib/wrapsock.o ../lib/wrapunix.o ../lib/str_echo.o ../03/writen.o ../03/readn.o
 */
int
main(int argc, char **argv)
{
    int listenfd, connfd;
    pid_t childpid;
    socklen_t childlen;
    struct sockaddr_in cliaddr, servaddr;
    listenfd = Socket(AF_INET, SOCK_STREAM, 0);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(SERV_PORT);

    Bind(listenfd, (SA*) &servaddr, sizeof(servaddr));
    Listen(listenfd, LISTENQ);
    for(;;)
    {
        childlen = sizeof(cliaddr);
		connfd = Accept(listenfd, (SA *) &cliaddr, &childlen);
        if((childpid = Fork()) == 0)
        {
            Close(listenfd);	/* close listening socket */
            //err_msg("child subprocess...");
			str_echo(connfd);	/* process the request */
			exit(0);
        }
        Close(connfd);
        //err_msg("main process...");
    }

}